﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
public partial class admin_Report : System.Web.UI.Page
{
    rUser user; string where = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (Session["userid"] == null) { Response.Redirect("../Default.aspx"); }
            ListItem li = new ListItem();
            li.Text= "Select One";
            li.Value= "Select One";
            cb_processor.Items.Add(li);
            cb_driver.Items.Add(li);
            cb_qc.Items.Add(li);
            cb_processor_rev.Items.Add(li);
            cb_processorfail.Items.Add(li);
            Utility.fillAgent("", 3, 2, cb_processor);
            Utility.fillAgent("", 1, 1, cb_driver);
            Utility.fillAgent("", 7, 1, cb_qc);
            Utility.fillAgent("", 10, 1, cb_qc);
            Utility.fillAgent("", 3, 2, cb_processor_rev);
            Utility.fillAgent("", 7, 1, cb_processor_rev);

            Utility.fillAgent("", 3, 2, cb_processorfail);
            Utility.fillAgent("", 7, 1, cb_processorfail);
            Utility.fillAgent("", 10, 1, cb_processorfail);
            Utility.fillAgent("", 15, 1, cb_processorfail);
            Utility.fillAgent("", 2, 1, cb_processorfail);
            Utility.fillAgent("", 13, 1, cb_processorfail);

            fillclients();
            fillcompanies();
            fillaccounts();
            Utility.fillsector(cb_sector);
            //Utility.fillCounties(cb_county);
            cb_county.Enabled = false;
            cb_area.Enabled = false;
            //Utility.fillAreas(cb_area);
           
            presult.Visible = false;
           
        }
        else
        {
            if (Session["report"] != null) { CrystalReportViewer1.ReportSource = Session["report"]; }
            if (Session["reportEval"] != null) { CrystalReportViewer2.ReportSource = Session["reportEval"]; }
            if (Session["reportDns"] != null) { CrystalReportViewer3.ReportSource = Session["reportDns"]; }
            if (Session["reportFail"] != null) { CrystalReportViewer4.ReportSource = Session["reportFail"]; }
            if (Session["reportClient"] != null) { CrystalReportViewer5.ReportSource = Session["reportClient"]; }
        
        }
    }

   

    protected void Page_Init(object sender, EventArgs e)
    {
        
        restricted();
        permiso();
    }

    private void fillclients()
    {
        try
        {
            DataSet usuClient= (DataSet)Session["usuClient"];
            if (usuClient == null) {  
                 com.bpophotos.www.Service service = new com.bpophotos.www.Service();
                 try
                 {

                     string rxml1 = service.getPerfiles(1,1);
                     DataSet perfiles = Utility.getPerfiles(rxml1);
                     Session["Perfiles"] = perfiles;
                     usuClient = Utility.getUsuClient(rxml1);
                 }
                 catch (Exception ex) {

                     Utility.writeError("Fail. al obtener clientes en Report.aspx");
                 }
            
            }
          
                ListItem listitem0 = new ListItem();
                listitem0.Text = "All Clients"; listitem0.Value = "";
                cb_client.Items.Add(listitem0);


                for (int ii = 0; ii <= (usuClient.Tables[0].Rows.Count - 1); ii++)
                {
                    ListItem listitem = new ListItem();
                    listitem.Text = usuClient.Tables[0].Rows[ii][2].ToString() + " " + usuClient.Tables[0].Rows[ii][1].ToString();
                    listitem.Value = usuClient.Tables[0].Rows[ii][0].ToString();
                    cb_client.Items.Add(listitem);
                    rUser ruser = (rUser)Session["userid"];
                    if (ruser!=null && ruser.getUsuarioId().Equals(listitem.Value)  )
                    {
                        cb_client.SelectedValue = listitem.Value;
                    }

                }
            }

        
        catch (Exception ee)
        {
            Utility.writeError(ee.Message+ ee.StackTrace);
        }
    }

    private void fillcompanies()
    {
        try
        {
            string rxml = null;
            com.bpophotos.www.Service service = new com.bpophotos.www.Service();
            rxml = service.getCompanies();


            if (!rxml.Equals("") || rxml != null)
            {
                DataSet dsclient = Utility.getCompanies(rxml);
                ListItem listitem0 = new ListItem();
                listitem0.Text = "All Companies"; listitem0.Value = "";
                cb_company.Items.Add(listitem0);


                for (int ii = 0; ii <= (dsclient.Tables[0].Rows.Count - 1); ii++)
                {
                    ListItem listitem = new ListItem();
                    listitem.Text = dsclient.Tables[0].Rows[ii][1].ToString();
                    listitem.Value = dsclient.Tables[0].Rows[ii][0].ToString();
                    cb_company.Items.Add(listitem);

                }
            }

        }
        catch (Exception ee)
        {
            Utility.writeError(ee.Message + ee.StackTrace);

        }
    }
    private void fillaccounts()
    {
        try
        {
            DataSet dsacc= (DataSet)Session["Accounts"];
            if (dsacc == null)
            {
                string rxml = null;
                com.bpophotos.www.Service service = new com.bpophotos.www.Service();
                rxml = service.getAccounts();


                if (!rxml.Equals("") || rxml != null)
                {
                    dsacc = Utility.getAccounts(rxml);
                     Session["Accounts"] = dsacc;
                }
            }
                    ListItem listitem0 = new ListItem();
                    listitem0.Text = "All Accounts"; listitem0.Value = "";
                    cb_account.Items.Add(listitem0);


                    for (int ii = 0; ii <= (dsacc.Tables[0].Rows.Count - 1); ii++)
                    {
                        ListItem listitem = new ListItem();
                        listitem.Text = dsacc.Tables[0].Rows[ii][1].ToString();
                        listitem.Value = dsacc.Tables[0].Rows[ii][0].ToString();
                        cb_account.Items.Add(listitem);

                    }
                }
               
            

        
        catch (Exception ee)
        {
            Utility.writeError(ee.Message);

        }
    }

    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        lerror.Text = "";
        int continuar = 1;
        if (cb_searchby.SelectedValue.Equals("p") && cb_invoicetype.SelectedValue.Equals("1") &&cb_processor.SelectedIndex==0){
            lerror.Text = "Select  Processor name.";
            continuar = 0;
        }
        if (cb_searchby.SelectedValue.Equals("d") && cb_invoicetype.SelectedValue.Equals("1") && cb_driver.SelectedIndex == 0)
        {
            lerror.Text = "Select  Driver name.";
            continuar = 0;
        }
        if (cb_searchby.SelectedValue.Equals("q") && cb_invoicetype.SelectedValue.Equals("1") && cb_qc.SelectedIndex == 0)
        {
            lerror.Text = "Select  QC agent name.";
            continuar = 0;
        }
        if (cb_searchby.SelectedValue.Equals("c") && cb_invoicetype.SelectedValue.Equals("1") && cb_company.SelectedIndex == 0)
        {
            lerror.Text = "Select  Company name.";
            continuar = 0;
        }
        if (cb_searchby.SelectedValue.Equals("co") && cb_invoicetype.SelectedValue.Equals("1") && cb_company.SelectedIndex == 0)
        {
            lerror.Text = "Select  Company name.";
            continuar = 0;
        }
        if (cb_searchby.SelectedValue.Equals("cl") && cb_invoicetype.SelectedValue.Equals("1") && cb_client.SelectedIndex == 0)
        {
            lerror.Text = "Select  Client name.";
            continuar = 0;
        }
       
        if (continuar==1){
               
        if (cb_invoicetype.SelectedIndex !=0)
        {
           // lb_name.Text = " All  " + cb_searchby.SelectedValue.ToUpper();
            if (cb_invoicetype.SelectedIndex == 1) //si es Source Out
            {
                //Si es Company General
                if (cb_searchby.SelectedValue.Equals("co") )
                {
                    mostrarReporte();
                    
                }
                else if (cb_searchby.SelectedValue.Equals("cl")) 
                {
                    mostrarReporte();
                    continuar = 1;
                }else if (cb_searchby.SelectedValue.Equals("d")) 
                {
                    mostrarReporte();
                    
                }
                else if (cb_searchby.SelectedValue.Equals("p"))
                {
                    //ModalPopupExtender1.Show();
                   
                }
                else if (cb_searchby.SelectedValue.Equals("q"))
                {
                    //ModalPopupExtender1.Show();
                    
                }
                
                         
            }
            else if (cb_invoicetype.SelectedIndex == 2) // Si es Source In
            {
                if (cb_searchby.SelectedValue.Equals("co")&& cb_company.SelectedIndex!=0)
                {
                    mostrarReporte();
                    
                }
                else if (cb_searchby.SelectedValue.Equals("cl") && cb_client.SelectedIndex != 0)
                {
                    mostrarReporte();

                } if (cb_searchby.SelectedValue.Equals("d") && cb_driver.SelectedIndex != 0)
                {
                    mostrarReporte();

                }
                else if (cb_searchby.SelectedValue.Equals("p") && cb_company.SelectedIndex != 0)
                {
                    String[] name = cb_processor.SelectedItem.ToString().Split('-');
                   // lb_name.Text = name[1];
                    //ModalPopupExtender1.Show();
                }
                else if (cb_searchby.SelectedValue.Equals("q") && cb_qc.SelectedIndex != 0)
                {
                    String[] name = cb_qc.SelectedItem.ToString().Split('-');
                    //lb_name.Text = name[1];
                    //ModalPopupExtender1.Show();
                }
            }
        }
        //activo boton para generar
     /*   long permiso = 0;
        user = (rUser)Session["userid"];
        if (user != null) {
            permiso = long.Parse(user.getPermisoUser().ToString());
            if ((permiso & 4294967296) == 4294967296) { bt_generate.Visible = true; }
        }*/
        //bt_generate.Visible = true; 
        mostrarReporte();
        }
            
    }

    public void restricted()
    {
        long permiso = 0;
        rUser user = (rUser)(Session["userid"]);
        if (user != null)
        {
            //permiso = long.Parse(user.getRestricted().ToString());
            RE_GenericBean permi = Utility.getPermisobyRuser(user, 11);
            permiso = permi.int64C2;
        }

        if ((permiso & 1) == 1) { Response.Redirect(Request.UrlReferrer.ToString()); }
        /*if ((permiso & 2) != 2) { createTabPanel(PReport,  "Report"); } else { PReport.Visible = false; }
       // if ((permiso & 4) != 4) { createTabPanel(PClient,  "Client Fail"); } else { PClient.Visible = false; }
       // if ((permiso & 8) != 8) { createTabPanel(PEval,  "Eval($45)"); } else { PEval.Visible = false; }
        if ((permiso & 16) != 16) { createTabPanel(PDNS, "Revisions"); } else { PDNS.Visible = false; }
         * */



        if ((permiso & 2) == 2) { TabPanel1.Enabled = false; }
        if ((permiso & 4) == 4) { TabPanel2.Enabled = false; }
        if ((permiso & 8) == 8) { TabPanel3.Enabled = false; }
        if ((permiso & 16) == 16) { TabPanel4.Enabled = false; }
    }

    private void createTabPanel(Panel Panel,  string headertext)
    {

        AjaxControlToolkit.TabPanel tabpanel = new AjaxControlToolkit.TabPanel();
        
        tabpanel.ID = headertext; tabpanel.HeaderText = headertext;
        tabpanel.Controls.Add(Panel);
       // TabContainer1.Tabs.Add(tabpanel);
        //TabContainer1.Visible = true;
    }

    public void permiso()
    {
        long permiso = 0;
        rUser user = (rUser)(Session["userid"]);
        if (user != null)
        {
           // permiso = long.Parse(user.getPermisoUser().ToString());
            RE_GenericBean permi = Utility.getPermisobyRuser(user, 11);
            permiso = permi.int64C1;
        }

        long test = permiso & 1;
     /*  if ((permiso & 2) != 2) { PReport.Enabled = false; }
        //if ((permiso & 4) != 4) { PClient.Enabled = false; }
        //if ((permiso & 8) != 8) { PEval.Enabled = false; }
        if ((permiso & 16) != 16) { PDNS.Enabled = false; }
        */

        if ((permiso & 2) != 2) { PReport.Enabled = false; }
        if ((permiso & 4) != 4) { PClient.Enabled = false; }
        if ((permiso & 8) != 8) { PEval.Enabled = false; }
        if ((permiso & 16) != 16) {PDNS.Enabled = false; }
    }
    protected void LinkButton3_Click(object sender, EventArgs e)
    {
        mostrarReporte();
        //tb_fee.Text = "";
    }

    private void mostrarReporte()
    {
        string parametro = "";
        string currency = "";
        //type es el tipo de reporte que se quiere 0= company, 1= client, 2= driver, 3 = processor, 4= qc
        int type = 0; 
        string style = "General";
        if (cb_searchby.SelectedIndex != 0)
        {
            where = " case when orden.ord_failed_" + cb_searchby.SelectedValue.ToString() + " is null then  orden.ord_" + cb_searchby.SelectedValue.ToString() + "_done else orden.ord_re" + cb_searchby.SelectedValue.ToString() + "_done  end = 'YES'";

            parametro = cb_searchby.SelectedValue.ToString();
            currency = "GTQ";
            style = "General";
            if (cb_searchby.SelectedValue.ToUpper().Equals("D"))
            {
                currency = "USD";
                
                if (!tb_stardate.Text.Equals(""))
                {
                    String[] fecha = tb_stardate.Text.Split('/');
                    where = where + " and  case when orden.ord_failed_driver is null then orden.ord_driver_date else orden.ord_redriver_date end >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
                }
                if (!tb_enddate.Text.Equals(""))
                {
                    String[] fecha2 = tb_enddate.Text.Split('/');
                    where = where + " and  case when orden.ord_failed_driver is null then orden.ord_driver_date else orden.ord_redriver_date end <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
                }


            }
            else if (cb_searchby.SelectedValue.ToUpper().Equals("P"))
            {
               
                if (!tb_stardate.Text.Equals(""))
                {
                    String[] fecha = tb_stardate.Text.Split('/');
                    where = where + " and case when orden.ord_failed_processor is null then orden.ord_processor_date else orden.ord_reprocessor_date end >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
                }
                if (!tb_enddate.Text.Equals(""))
                {
                    String[] fecha2 = tb_enddate.Text.Split('/');
                    where = where + " and case when orden.ord_failed_processor is null then orden.ord_processor_date else orden.ord_reprocessor_date end <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
                }

            }
            else if (cb_searchby.SelectedValue.ToUpper().Equals("Q"))
            {
               
                if (!tb_stardate.Text.Equals(""))
                {
                    String[] fecha = tb_stardate.Text.Split('/');
                    where = where + " and  case when orden.ord_failed_qc is null then orden.ord_qc_date else orden.ord_reqc_date end >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
                }
                if (!tb_enddate.Text.Equals(""))
                {
                    String[] fecha2 = tb_enddate.Text.Split('/');
                    where = where + " and  case when orden.ord_failed_qc is null then orden.ord_qc_date else orden.ord_reqc_date end <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
                }
            }
            else if (cb_searchby.SelectedValue.ToUpper().Equals("CO"))
            {
               
                where = where + " and   orden.company ="+cb_company.SelectedValue+ " and  case when orden.ord_failed is null then orden.submitted_done else orden.resubmitted_done end = 'YES'";
                if (!tb_stardate.Text.Equals(""))
                {
                    String[] fecha = tb_stardate.Text.Split('/');
                    where = where + " and    case when orden.ord_failed is null then  orden.ord_submitted_date else orden.ord_resubmitted_date end >= '"+fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
                }
                if (!tb_enddate.Text.Equals(""))
                {
                    String[] fecha2 = tb_enddate.Text.Split('/');
                    where = where + " and  case when orden.ord_failed is null then orden.submitted_date else orden.ord_resubmitted_date end <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
                }
            }
            else if (cb_searchby.SelectedValue.ToUpper().Equals("CL"))
            {
             
                where = where + " and   orden.client =" + cb_client.SelectedValue + " and  case when orden.ord_failed is null then orden.submitted_done else orden.resubmitted_done end = 'YES'";
                if (!tb_stardate.Text.Equals(""))
                {
                    String[] fecha = tb_stardate.Text.Split('/');
                    where = where + " and    case when orden.ord_failed is null then  orden.ord_submitted_date else orden.ord_resubmitted_date end >= '" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
                }
                if (!tb_enddate.Text.Equals(""))
                {
                    String[] fecha2 = tb_enddate.Text.Split('/');
                    where = where + " and  case when orden.ord_failed is null then orden.submitted_date else orden.ord_resubmitted_date end <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
                }
            }
        }
        if (cb_invoicetype.SelectedValue.Equals("0")){ // Si son invoice Assig (Sign In)

            if (cb_company.SelectedIndex!=0){
                if (!where.Equals("")) { where = where + " and "; }
                where = where + "   ( orden.company =" + cb_company.SelectedValue + ") ";
            }
            if (cb_client.SelectedIndex != 0) {
                if (!where.Equals("")) { where = where + " and "; }
                where = where + "   ( orden.client_id = '" + cb_client.SelectedValue + "' ) ";
            }
            if (cb_account.SelectedIndex != 0) {
                if (!where.Equals("")) { where = where + " and "; }
                where = where + "  ( orden.account =  "+ cb_account.SelectedValue + " ) ";
            
            }
            if (!tb_stardate.Text.Equals(""))
            {
                String[] fecha = tb_stardate.Text.Split('/');
                if (!where.Equals("")) { where = where + " and "; }
                where = where + "  orden.ord_date  >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
            }
            if (!tb_enddate.Text.Equals(""))
            {
                String[] fecha2 = tb_enddate.Text.Split('/');
                if (!where.Equals("")) { where = where + " and "; }
                where = where + "    orden.ord_date  <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
            }
            type = 5;
            

        }
        
        if (cb_invoicetype.SelectedValue.Equals("1")){  // si son reports Submitted (source out)

            if (cb_company.SelectedIndex != 0)
            {
                if (!where.Equals("")){ where = where + " and "; }
                where = where + "   ( orden.company =" + cb_company.SelectedValue + ") ";
            }
            if (cb_client.SelectedIndex != 0)
            {
                if (!where.Equals("")) { where = where + " and "; }
                where = where + "   ( orden.client_id = '" + cb_client.SelectedValue + "' ) ";
            }
            if (cb_account.SelectedIndex != 0)
            {
                if (!where.Equals("")) { where = where + " and "; }
                where = where + " ( orden.account =  " + cb_account.SelectedValue + " ) ";

            }

            if (!tb_stardate.Text.Equals(""))
            {
                String[] fecha = tb_stardate.Text.Split('/');
                if (!where.Equals("")) { where = where + " and "; }
                where = where + "  orden.ord_submitted_date  >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
            }
            if (!tb_enddate.Text.Equals(""))
            {
                String[] fecha2 = tb_enddate.Text.Split('/');
                if (!where.Equals("")) { where = where + " and "; }
                where = where + "    orden.ord_submitted_date <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
            }
            type = 6;  
            
            
        }

        if (cb_invoicetype.SelectedValue.Equals("2"))
        {  // si son reports Paid

            if (cb_company.SelectedIndex != 0)
            {
                if (!where.Equals("")) { where = where + " and "; }
                where = where + "   ( orden.company =" + cb_company.SelectedValue + ") ";
            }
            if (cb_client.SelectedIndex != 0)
            {
                if (!where.Equals("")) { where = where + " and "; }
                where = where + "   ( orden.client_id = '" + cb_client.SelectedValue + "' ) ";
            }
            if (cb_account.SelectedIndex != 0)
            {
                if (!where.Equals("")) { where = where + " and "; }
                where = where + " ( orden.account =  " + cb_account.SelectedValue + " ) ";

            }

            if (!tb_stardate.Text.Equals(""))
            {
                String[] fecha = tb_stardate.Text.Split('/');
                if (!where.Equals("")) { where = where + " and "; }
                where = where + "  orden.paid_date  >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
            }
            if (!tb_enddate.Text.Equals(""))
            {
                String[] fecha2 = tb_enddate.Text.Split('/');
                if (!where.Equals("")) { where = where + " and "; }
                where = where + "    orden.paid_date <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
            }
            type = 7;


        }
        if (cb_invoicetype.SelectedValue.Equals("4"))
        {  // si son reports UnPaid

            if (cb_company.SelectedIndex != 0)
            {
                if (!where.Equals("")) { where = where + " and "; }
                where = where + "   ( orden.company =" + cb_company.SelectedValue + ") ";
            }
            if (cb_client.SelectedIndex != 0)
            {
                if (!where.Equals("")) { where = where + " and "; }
                where = where + "   ( orden.client_id = '" + cb_client.SelectedValue + "' ) ";
            }
            if (cb_account.SelectedIndex != 0)
            {
                if (!where.Equals("")) { where = where + " and "; }
                where = where + " ( orden.account =  " + cb_account.SelectedValue + " ) ";

            }

            if (!tb_stardate.Text.Equals(""))
            {
                String[] fecha = tb_stardate.Text.Split('/');
                if (!where.Equals("")) { where = where + " and "; }
                where = where + "  orden.ord_submitted_date  >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
            }
            if (!tb_enddate.Text.Equals(""))
            {
                String[] fecha2 = tb_enddate.Text.Split('/');
                if (!where.Equals("")) { where = where + " and "; }
                where = where + "    orden.ord_submitted_date <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
            }
            type = 8;


        }

        try
        {

            if (type == 2)
            {

                REPORTDS ds = new REPORTDS();
                string period = tb_stardate.Text + " - " + tb_enddate.Text;
             
                Byte[] imagen = CargarImagen("C:\\TEMP\\logo2.jpg");//Cargo La imagen
                ds = DB.getInvoice(where, period, "", currency, parametro, style, imagen,"");
                CrystalDecisions.CrystalReports.Engine.ReportDocument rpt = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
              
                rpt.Load(Server.MapPath("~/Reports/DriverInvoice.rpt"));
              //  if (ch_sumary.Checked) { rpt.Load(Server.MapPath("~/Reports/DriverInvoiceSum.rpt")); }
                rpt.SetDataSource(ds);
                CrystalReportViewer1.ReportSource = rpt;
                CrystalReportViewer1.DataBind();
                Session["report"] = rpt;

            }
            else if(type==3) // si es proc
            {
                REPORTDS ds = new REPORTDS();
                string period = tb_stardate.Text + " - " + tb_enddate.Text;
                // Byte[] imagen = CargarImagen(Server.MapPath("~/Reports/images/logo.bmp"));//Cargo La imagen
                Byte[] imagen = CargarImagen("C:\\TEMP\\logo2.jpg");//Cargo La imagen
                ds = DB.getInvoice(where, period, "", currency, parametro, style, imagen,"");
                CrystalDecisions.CrystalReports.Engine.ReportDocument rpt = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
                //rpt.SetDatabaseLogon("pacific", "P@cp@cc1f1c", "./sqlexpress", "BPOPhotos");
                rpt.Load(Server.MapPath("~/Reports/ProcessorInvoice.rpt"));
               // if (ch_sumary.Checked) { rpt.Load(Server.MapPath("~/Reports/ProcessorInvoiceSum.rpt")); }
                rpt.SetDataSource(ds);
                CrystalReportViewer1.DisplayGroupTree = false;

                CrystalReportViewer1.ReportSource = rpt;
                CrystalReportViewer1.DataBind();
                Session["report"] = rpt;

            }else if (type==4)// si es qc
            {
                REPORTDS ds = new REPORTDS();
                string period = tb_stardate.Text + " - " + tb_enddate.Text;
                // Byte[] imagen= CargarImagen(Server.MapPath("~/Reports/images/logo.bmp"));//Cargo La imagen
                Byte[] imagen = CargarImagen("C:\\TEMP\\logo2.jpg");//Cargo La imagen
                ds = DB.getInvoice(where, period, "", currency, parametro, style, imagen,"");
                CrystalDecisions.CrystalReports.Engine.ReportDocument rpt = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
                // rpt.SetDatabaseLogon("pacific", "P@cp@cc1f1c", "./sqlexpress", "BPOPhotos");
               // rpt.Load(Server.MapPath("~/Reports/QCInvoice.rpt"));
               // if (ch_sumary.Checked) { rpt.Load(Server.MapPath("~/Reports/QCInvoiceSum.rpt")); }
                rpt.SetDataSource(ds);
                CrystalReportViewer1.DisplayGroupTree = false;
                CrystalReportViewer1.ReportSource = rpt;
                CrystalReportViewer1.DataBind();
                Session["report"] = rpt;
            
            }else if (type==0) // si es company
            {
                REPORTDS ds = new REPORTDS();
                string period = tb_stardate.Text + " - " + tb_enddate.Text;
                // Byte[] imagen= CargarImagen(Server.MapPath("~/Reports/images/logo.bmp"));//Cargo La imagen
                Byte[] imagen = CargarImagen("C:\\TEMP\\logo2.jpg");//Cargo La imagen
                ds = DB.getInvoice(where, period, "0.00", currency, parametro, style, imagen,"");
                CrystalDecisions.CrystalReports.Engine.ReportDocument rpt = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
                // rpt.SetDatabaseLogon("pacific", "P@cp@cc1f1c", "./sqlexpress", "BPOPhotos");
                rpt.Load(Server.MapPath("~/Reports/CompanyInvoice.rpt"));
               // if (ch_sumary.Checked) { rpt.Load(Server.MapPath("~/Reports/CompanyInvoiceSum.rpt")); }
                rpt.SetDataSource(ds);
                CrystalReportViewer1.DisplayGroupTree = false;
                CrystalReportViewer1.ReportSource = rpt;
                CrystalReportViewer1.DataBind();
                Session["report"] = rpt;
            
            }else if (type==1)// si es client
            {
                REPORTDS ds = new REPORTDS();
                string period = tb_stardate.Text + " - " + tb_enddate.Text;
                // Byte[] imagen= CargarImagen(Server.MapPath("~/Reports/images/logo.bmp"));//Cargo La imagen
                Byte[] imagen = CargarImagen("C:\\TEMP\\logo2.jpg");//Cargo La imagen
                ds = DB.getInvoice(where, period, "", currency, parametro, style, imagen,"");
                CrystalDecisions.CrystalReports.Engine.ReportDocument rpt = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
            
                rpt.Load(Server.MapPath("~/Reports/ClientInvoice.rpt"));
               // if (ch_sumary.Checked) { rpt.Load(Server.MapPath("~/Reports/ClientInvoiceSum.rpt")); }
                rpt.SetDataSource(ds);
                CrystalReportViewer1.DisplayGroupTree = false;
                CrystalReportViewer1.ReportSource = rpt;
                CrystalReportViewer1.DataBind();
                Session["report"] = rpt;
            }else if (type == 5) // si es Source In Assign
            {
                REPORTDS ds = new REPORTDS();
                string period = tb_stardate.Text + " - " + tb_enddate.Text;
                // Byte[] imagen= CargarImagen(Server.MapPath("~/Reports/images/logo.bmp"));//Cargo La imagen
                Byte[] imagen = CargarImagen("C:\\TEMP\\logo2.jpg");//Cargo La imagen
                string campofee = "fee";
                if (rbl_fee.SelectedIndex == 1) campofee = "psfprice"; 
                ds = DB.getSourceReport(where, period, "ord_date", currency, "ord_date", "Assigned", imagen,campofee);
                CrystalDecisions.CrystalReports.Engine.ReportDocument rpts = new CrystalDecisions.CrystalReports.Engine.ReportDocument();

                rpts.Load(Server.MapPath("~/Reports/AssignSumaryReport.rpt"));

                rpts.SetDataSource(ds);

                CrystalDecisions.CrystalReports.Engine.ReportDocument rpt = new CrystalDecisions.CrystalReports.Engine.ReportDocument();

                if ((cb_client.SelectedIndex == 0 || cb_client.SelectedIndex == 1) && (cb_company.SelectedIndex == 0 || cb_company.SelectedIndex==-1)  && (cb_account.SelectedIndex == 0 || cb_account.SelectedIndex == -1))
                {
                    rpt.Load(Server.MapPath("~/Reports/AssignReportClient.rpt"));

                    rpt.SetDataSource(ds);
                    CrystalReportViewer1.ReportSource = rpt;
                    CrystalReportViewer1.DataBind();
                    Session["report"] = rpt;
                }
                else if (cb_client.SelectedIndex != 0 && cb_client.SelectedIndex != 1 && (cb_company.SelectedIndex == 0 || cb_client.SelectedIndex == -1) && (cb_account.SelectedIndex == 0 || cb_account.SelectedIndex == -1))
                {
                     rpt.Load(Server.MapPath("~/Reports/AssignReport.rpt"));

                    rpt.SetDataSource(ds);
                    CrystalReportViewer1.ReportSource = rpt;
                    CrystalReportViewer1.DataBind();
                    Session["report"] = rpt;


                }
                else if (cb_client.SelectedIndex != 0 && cb_client.SelectedIndex != 1 && cb_company.SelectedIndex != 0 && (cb_account.SelectedIndex==0 || cb_account.SelectedIndex==-1))
                {
                    rpt.Load(Server.MapPath("~/Reports/AssignReportAcc.rpt"));

                    rpt.SetDataSource(ds);
                    CrystalReportViewer1.ReportSource = rpt;
                    CrystalReportViewer1.DataBind();
                    Session["report"] = rpt;
                
                }
                else {

                    rpt.Load(Server.MapPath("~/Reports/AssignReportNG.rpt"));

                    rpt.SetDataSource(ds);
                    CrystalReportViewer1.ReportSource = rpt;
                    CrystalReportViewer1.DataBind();
                    Session["report"] = rpt;
                
                }
            
            }else if (type == 6){ // si es Source Out Submitted
                REPORTDS ds = new REPORTDS();
                string period = tb_stardate.Text + " - " + tb_enddate.Text;
                // Byte[] imagen= CargarImagen(Server.MapPath("~/Reports/images/logo.bmp"));//Cargo La imagen
                Byte[] imagen = CargarImagen("C:\\TEMP\\logo2.jpg");//Cargo La imagen
                string campofee = "fee";
                if (rbl_fee.SelectedIndex == 1) campofee = "psfprice"; 
                ds = DB.getSourceReport(where, period, "ord_submitted_date", currency, "ord_submitted_date", "Submitted", imagen,campofee);
                CrystalDecisions.CrystalReports.Engine.ReportDocument rpts = new CrystalDecisions.CrystalReports.Engine.ReportDocument();

                rpts.Load(Server.MapPath("~/Reports/AssignSumaryReport.rpt"));

                rpts.SetDataSource(ds);
                CrystalDecisions.CrystalReports.Engine.ReportDocument rpt = new CrystalDecisions.CrystalReports.Engine.ReportDocument();

                rpt.Load(Server.MapPath("~/Reports/AssignReport.rpt"));

                rpt.SetDataSource(ds);
                CrystalReportViewer1.DisplayGroupTree = false;
                CrystalReportViewer1.ReportSource = rpt;
                CrystalReportViewer1.DataBind();
                Session["report"] = rpt;

            }
            else if (type == 7)
            { // si es Paid 
                REPORTDS ds = new REPORTDS();
                string period = tb_stardate.Text + " - " + tb_enddate.Text;
                // Byte[] imagen= CargarImagen(Server.MapPath("~/Reports/images/logo.bmp"));//Cargo La imagen
                Byte[] imagen = CargarImagen("C:\\TEMP\\logo2.jpg");//Cargo La imagen
                if (!where.Equals("")) { where += " and ";  }
                where += " orden.paid='YES' ";
                string campofee = "fee";
                if (rbl_fee.SelectedIndex == 1) campofee = "psfprice"; 
                ds = DB.getSourceReport(where, period, "paid_date", currency, "paid_date", "Paid", imagen, campofee);
                CrystalDecisions.CrystalReports.Engine.ReportDocument rpts = new CrystalDecisions.CrystalReports.Engine.ReportDocument();

                rpts.Load(Server.MapPath("~/Reports/AssignSumaryReport.rpt"));

                rpts.SetDataSource(ds);
                CrystalDecisions.CrystalReports.Engine.ReportDocument rpt = new CrystalDecisions.CrystalReports.Engine.ReportDocument();

                rpt.Load(Server.MapPath("~/Reports/AssignReport.rpt"));

                rpt.SetDataSource(ds);
                CrystalReportViewer1.DisplayGroupTree = false;
                CrystalReportViewer1.ReportSource = rpt;
                CrystalReportViewer1.DataBind();
                Session["report"] = rpt;

            }
            else if (type == 8)
            { // si es Unpaid
                REPORTDS ds = new REPORTDS();
                string period = tb_stardate.Text + " - " + tb_enddate.Text;
                // Byte[] imagen= CargarImagen(Server.MapPath("~/Reports/images/logo.bmp"));//Cargo La imagen
                Byte[] imagen = CargarImagen("C:\\TEMP\\logo2.jpg");//Cargo La imagen
                if (!where.Equals("")) { where += " and "; }
                where += " ( upper(orden.paid)='NO' or orden.paid is null ) ";
                string campofee = "fee";
                if (rbl_fee.SelectedIndex == 1) campofee = "psfprice"; 
                ds = DB.getSourceReport(where, period, "ord_submitted_date", currency, "ord_submitted_date", "Unpaid", imagen, campofee);
                CrystalDecisions.CrystalReports.Engine.ReportDocument rpts = new CrystalDecisions.CrystalReports.Engine.ReportDocument();

                rpts.Load(Server.MapPath("~/Reports/AssignSumaryReport.rpt"));

                rpts.SetDataSource(ds);
                CrystalDecisions.CrystalReports.Engine.ReportDocument rpt = new CrystalDecisions.CrystalReports.Engine.ReportDocument();

                rpt.Load(Server.MapPath("~/Reports/AssignReport.rpt"));

                rpt.SetDataSource(ds);
                CrystalReportViewer1.DisplayGroupTree = false;
                CrystalReportViewer1.ReportSource = rpt;
                CrystalReportViewer1.DataBind();
                Session["report"] = rpt;

            }

            cb_searchby.SelectedIndex = 0;
            cb_driver.SelectedIndex = 0;
            cb_processor.SelectedIndex = 0;
            cb_qc.SelectedIndex = 0;
            tb_stardate.Text = "";
            tb_enddate.Text = "";
            cb_account.SelectedIndex = 0;
            cb_company.SelectedIndex = 0;
            cb_client.SelectedIndex = 0;
            cb_invoicetype.SelectedIndex = 0;
        }
        catch (Exception ex)
        {
            Utility.writeError("Error al generar Invoice " + ex.Message + ex.StackTrace);
        }



    }

    public static Byte[] CargarImagen(string rutaArchivo)
    {


        if (rutaArchivo != "")
        {

            try
            {

                FileStream Archivo = new FileStream(rutaArchivo, FileMode.Open);//Creo el archivo
                BinaryReader binRead = new BinaryReader(Archivo);//Cargo el Archivo en modo binario

                Byte[] imagenEnBytes = new Byte[(Int64)Archivo.Length]; //Creo un Array de Bytes donde guardare la imagen

                binRead.Read(imagenEnBytes, 0, (int)Archivo.Length);//Cargo la imagen en el array de Bytes
                binRead.Close();

                Archivo.Close();

                return imagenEnBytes;//Devuelvo la imagen convertida en un array de bytes

            }


            catch (Exception ex)
            {
                Utility.writeError("No leyo imagen" + ex.Message + ex.StackTrace);
                return new Byte[0];
            }

        }

        return new byte[0];

    }
    protected void lnk_clientfail_Click(object sender, EventArgs e)
    {
        lerror.Visible = false;
        where = "";
        presult.Visible = false;
       
            if (!tb_stardatefee.Text.Equals(""))
            {
                String[] fecha = tb_stardatefee.Text.Split('/');
                where = where + "   [ORDER_FAIL].date   >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
            }
            if (!tb_enddatefee.Text.Equals(""))
            {
                if (where != "") { where += " and "; }
                String[] fecha2 = tb_enddatefee.Text.Split('/');
                where = where + "   [ORDER_FAIL].date <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
            }
            if (cb_sector.SelectedIndex != 0 && cb_sector.SelectedIndex != -1)
            {
                if (where != "") { where += " and "; }
                where = where + "   [ORDER].ord_sector ='"+ cb_sector.SelectedValue + "'";
            }
            if (cb_county.SelectedIndex != 0 && cb_county.SelectedIndex != -1)
            {
                if (where != "") { where += " and "; }
                where = where + "   [ORDER].county ='" + cb_county.SelectedValue + "'";
            }
            if (cb_area.SelectedIndex != 0 && cb_area.SelectedIndex!=-1)
            {
                if (where != "") { where += " and "; }
                where = where + "   [ORDER].ord_area ='" + cb_area.SelectedValue + "'";
            }
            REPORTDS dsr = DB.getReportClientdsr(where, tb_stardatefee.Text + "-" + tb_enddatefee.Text);
           // DataSet ds = DB.getReportClient(where);
           // gv.DataSource = ds.Tables[0];
            //gv.DataBind();
            //lb_nequals.Text =  ds.Tables[1].Rows[0][4].ToString();
            //lb_pequals.Text = ds.Tables[1].Rows[0][5].ToString() + " % ";
           // lb_npos.Text = ds.Tables[1].Rows[0][0].ToString();
           // lb_ppos.Text = ds.Tables[1].Rows[0][1].ToString() + " % ";
           // lb_nneg.Text = ds.Tables[1].Rows[0][2].ToString();
           // lb_pneg.Text = ds.Tables[1].Rows[0][3].ToString() + " % ";
            cb_sector.SelectedIndex = 0;
           
            
            presult.Visible = true;

            CrystalDecisions.CrystalReports.Engine.ReportDocument rptcl = new CrystalDecisions.CrystalReports.Engine.ReportDocument();

            rptcl.Load(Server.MapPath("~/Reports/ClientFailReport.rpt"));
            rptcl.SetDataSource(dsr);
           
            CrystalReportViewer5.ReportSource = rptcl;
            CrystalReportViewer5.DataBind();
            Session["reportClient"] = rptcl;

       
    }
    protected void cb_sector_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (cb_sector.SelectedIndex != 0)
        {
            DataSet areas = DB.getAreasbySector(cb_sector.SelectedValue);
            cb_area.Items.Clear();
            cb_area.Enabled = true;
            cb_county.Items.Clear();
            cb_county.Enabled = false;
            ListItem li = new ListItem();
            li.Text = "All";
            li.Value = "0";
            cb_area.Items.Add(li);
            for (int i = 0; i < areas.Tables[0].Rows.Count; i++)
            {
                li = new ListItem();
                li.Text = areas.Tables[0].Rows[i][1].ToString();
                li.Value = areas.Tables[0].Rows[i][0].ToString();
                cb_area.Items.Add(li);

            }
        }
        else {
            cb_area.Items.Clear();
            cb_area.Enabled = false;
            cb_county.Items.Clear();
            cb_county.Enabled = false;
        
        }
    }
    protected void cb_area_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (cb_area.SelectedIndex != 0)
        {
            DataSet counties = DB.getCountiesbyArea(cb_area.SelectedValue);
            cb_county.Items.Clear();
            cb_county.Enabled = true;
            ListItem li = new ListItem();
            li.Text = "All";
            li.Value = "0";
            cb_county.Items.Add(li);
            for (int i = 0; i < counties.Tables[0].Rows.Count; i++)
            {
                li = new ListItem();
                li.Text = counties.Tables[0].Rows[i][1].ToString();
                li.Value = counties.Tables[0].Rows[i][0].ToString();
                cb_county.Items.Add(li);

            }
        }
        else
        {
            cb_county.Items.Clear();
            cb_county.Enabled = false;

        }
    }
    protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        
        if (e.Row.RowType == DataControlRowType.Header) {
            e.Row.Style.Add("text-align", "left");
        }
    }

    protected void lnk_save_bank_Click(object sender, EventArgs e)
    {
        string where = "";
        if (!tb_evaldate1.Text.Equals("")) { 
            String[] fecha = tb_evaldate1.Text.Split('/');
                    
                    where = where + "   ord_submitted_date >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
        }
        if (!tb_evaldate2.Text.Equals(""))
        {
            String[] fecha = tb_evaldate2.Text.Split('/');
            if (!where.Equals("")) { where = where + " and "; }
            where = where + "   ord_submitted_date <='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
        }

        if (!where.Equals("")) { where = where + " and "; }
        where = where + " orden.company=9 and orden.psfprice = 45 ";
        REPORTDS ds = new REPORTDS();
        string period = tb_evaldate1.Text + " - " + tb_evaldate2.Text;
        // Byte[] imagen= CargarImagen(Server.MapPath("~/Reports/images/logo.bmp"));//Cargo La imagen
        Byte[] imagen = CargarImagen("C:\\TEMP\\logo2.jpg");//Cargo La imagen
        ds = DB.getEvalReport(where, period, "ord_submitted_date", "$", "ord_submitted_date", "Submitted", imagen);
        CrystalDecisions.CrystalReports.Engine.ReportDocument rpts = new CrystalDecisions.CrystalReports.Engine.ReportDocument();

        rpts.Load(Server.MapPath("~/Reports/EvalSumaryReport.rpt"));

        rpts.SetDataSource(ds);
        CrystalDecisions.CrystalReports.Engine.ReportDocument rpt = new CrystalDecisions.CrystalReports.Engine.ReportDocument();

        rpt.Load(Server.MapPath("~/Reports/EvalReport.rpt"));

        rpt.SetDataSource(ds);
       
        CrystalReportViewer2.ReportSource = rpt;
        CrystalReportViewer2.DataBind();
        Session["reportEval"] = rpt;


    }
    protected void lnk_searchDns_Click(object sender, EventArgs e)
    {
        string where = "";
        if (!tb_startdatedns.Text.Equals(""))
        {
            String[] fecha = tb_startdatedns.Text.Split('/');

            where = where + "   ord_rv_date >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
        }
        if (!endatedns.Text.Equals(""))
        {
            String[] fecha = endatedns.Text.Split('/');
            if (!where.Equals("")) { where = where + " and "; }
            where = where + "   ord_rv_date <='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
        }
        if (cb_processor_rev.SelectedIndex!=-1 && cb_processor_rev.SelectedIndex!=0){
            if (!where.Equals("")) { where = where + " and "; }
            where = where + " orden.ord_processor    ='" + cb_processor_rev.SelectedValue.ToString() + "'";
        } 
       
        REPORTDS ds = new REPORTDS();
        string period = tb_startdatedns.Text + " - " + endatedns.Text;
        // Byte[] imagen= CargarImagen(Server.MapPath("~/Reports/images/logo.bmp"));//Cargo La imagen
        Byte[] imagen = CargarImagen("C:\\TEMP\\logo2.jpg");//Cargo La imagen
        ds = DB.getDNSReport(where, period, "ord_submitted_date", "$", "ord_submitted_date", "Submitted", imagen);
        CrystalDecisions.CrystalReports.Engine.ReportDocument rpts = new CrystalDecisions.CrystalReports.Engine.ReportDocument();

        rpts.Load(Server.MapPath("~/Reports/DNSSumaryReport.rpt"));

        rpts.SetDataSource(ds);
        CrystalDecisions.CrystalReports.Engine.ReportDocument rpt = new CrystalDecisions.CrystalReports.Engine.ReportDocument();

        rpt.Load(Server.MapPath("~/Reports/DNSReport.rpt"));

        rpt.SetDataSource(ds);

        CrystalReportViewer3.ReportSource = rpt;
        CrystalReportViewer3.DataBind();
        Session["reportDns"] = rpt;


    }
    protected void lnk_searchfail_Click(object sender, EventArgs e)
    {
        string where = ""; string filtro="";
        if (!tb_date1fail.Text.Equals(""))
        {
            String[] fecha = tb_date1fail.Text.Split('/');

            where = where + "   [ORDER_FAIL].date  >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
        }
        if (!tb_date2fail.Text.Equals(""))
        {
            String[] fecha = tb_date2fail.Text.Split('/');
            if (!where.Equals("")) { where = where + " and "; }
            where = where + "   [ORDER_FAIL].date <='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
        }
       if (cb_processorfail.SelectedIndex!=0 && cb_processorfail.SelectedIndex!=-1)
       {
           
           filtro = cb_processorfail.SelectedValue;
       }

        REPORTDS ds = new REPORTDS();
        string period = tb_date1fail.Text + " - " + tb_date2fail.Text;
        
        ds = DB.getFailReport(where, period,filtro);
        if (ds!=null){
       /* CrystalDecisions.CrystalReports.Engine.ReportDocument rpts = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
        rpts.Load(Server.MapPath("~/Reports/FailOneReport.rpt"));
        rpts.SetDataSource(ds);

        CrystalDecisions.CrystalReports.Engine.ReportDocument rptt = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
        rptt.Load(Server.MapPath("~/Reports/FailTwoReport.rpt"));
        rptt.SetDataSource(ds);
        
        CrystalDecisions.CrystalReports.Engine.ReportDocument rptth = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
        rptth.Load(Server.MapPath("~/Reports/FailThreeReport.rpt"));
        rptth.SetDataSource(ds);
    
        CrystalDecisions.CrystalReports.Engine.ReportDocument rptf = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
        rptf.Load(Server.MapPath("~/Reports/FailFourReport.rpt"));
        rptf.SetDataSource(ds);

        CrystalDecisions.CrystalReports.Engine.ReportDocument rptfi = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
        rptfi.Load(Server.MapPath("~/Reports/FailFiveReport.rpt"));
        rptfi.SetDataSource(ds);
*/
        CrystalDecisions.CrystalReports.Engine.ReportDocument  rpt = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
        rpt.Load(Server.MapPath("~/Reports/FailTotalReport.rpt"));
        rpt.SetDataSource(ds);

        CrystalReportViewer4.ReportSource = rpt;
       CrystalReportViewer4.DataBind();
       Session["reportFail"] = rpt;
       
           
        }
    }

    
}